package com.itCar.base.test;

import java.sql.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @ClassName EntityJson
 * @Description TODO 补充说明:  获取mysql数据库表的名和注释并形成JSON格式输出
 * @Author liuzhiguo
 * @Date 2024/1/2 10:22
 * @Version 1.0
 */
@SpringBootTest
public class EntityJson {

    @Test
    public void getEntityJSon() {
        // MySQL数据库连接信息
        String url = "jdbc:mysql://39.104.67.224:3306/fuel_smart_test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true";
        String username = "root";
        String password = "hhxxhhxx";

        try (
            Connection conn = DriverManager.getConnection(url, username, password)) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet tablesResultSet = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            JSONArray tableList = new JSONArray();
            while (tablesResultSet.next()) {
                String tableName = tablesResultSet.getString("TABLE_NAME");
                ResultSet columnsResultSet = metaData.getColumns(null, null, tableName, "%");
                JSONObject tableInfo = new JSONObject();
                tableInfo.put("tableName", tableName);
                JSONArray columnList = new JSONArray();
                while (columnsResultSet.next()) {
                    String columnName = columnsResultSet.getString("COLUMN_NAME");
                    JSONObject columnInfo = new JSONObject();
                    columnInfo.put("columnName", columnName);
                    columnList.add(columnInfo);
                }
                tableInfo.put("columns", columnList);
                tableList.add(tableInfo);
            }
            System.out.println(tableList.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
